package com.umeox.watch.moto.chat.db

import androidx.annotation.VisibleForTesting
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.umeox.moto.common.log.Logger
import com.umeox.watch.moto.chat.base.BaseApp

/**
 * Created by Rambo 2021/8/18
 * Describe:
 */
@Database(
    entities = [ContactInfo::class, ChatMessage::class],
    version = AppDatabase.VERSION_CODE,
    exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun contactInfoDao(): ContactInfoDao

    abstract fun chatMessageDao(): ChatMessageDao

    companion object {
        private var instance: AppDatabase? = null

        const  val VERSION_CODE: Int = 2

        @VisibleForTesting
        val MIGRATION_1_2: Migration =
            object : Migration(1, VERSION_CODE) {
                override fun migrate(database: SupportSQLiteDatabase) {
                    Logger.i("MIGRATION_1_2")
                    //contact_info 表新增字段
                    database.execSQL("ALTER TABLE contact_info ADD COLUMN createTime INTEGER NOT NULL DEFAULT 0")
                    database.execSQL("ALTER TABLE contact_info ADD COLUMN isGroup INTEGER NOT NULL DEFAULT 0")
                }
            }
        @Synchronized
        fun get(): AppDatabase {
            if (null == instance) instance = Room.databaseBuilder(
                BaseApp.getContext().applicationContext,
                AppDatabase::class.java,
                "umeox_chats"
            )
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_1_2).build()
            return instance as AppDatabase
        }
    }
}